package pdf417lib.flex {
	
	import flash.display.Shape;
	import flash.events.ErrorEvent;	

	import mx.core.UIComponent;
	import mx.core.mx_internal;	
	import pdf417lib.Pdf417lib;	
	
	// using mx_internal so we can use $addChild and $removeChild
	use namespace mx_internal;
	
	/**
	 * This event is broadcast when the barcodeText string is too long to encode.
	 * The specific max length varies depending on the level of error correction 
	 * and the specific string being encoded.
	 * 
	 * @eventType pdf417lib.Pdf417Event.BARCODE_ERROR
	 */
	[Event(name="barcodeError", type="pdf417lib.flex.Pdf417Event")]
	
	/**
	 * Flex component for generating a pdf417 barcode
	 * using the AS3 port of pdf417lib.
	 * 
	 * @author David Knape (http://bumpslide.com/)
	 */
	public class Pdf417Barcode extends UIComponent {
				
		[Bindable]
		// whether or not to trace debug messages
		public var debugEnabled:Boolean=true;
				
		// the text we will be encoding
		private var _barcodeText:String;
		
		// the shape we are displaying
		private var _barcodeShape:Shape;
		
		/**
		 * Sets the text to be encoded and triggers a redrawing of the barcode
		 */
		[Bindable]
		public function set barcodeText(s:String):void {
			debug('setting barcodeText');// to:\n' + s );
			_barcodeText = s;
			invalidateProperties();
		}
		
		/**
		 * The encoded text
		 */
		public function get barcodeText():String {
			return _barcodeText;
		}
		
		/**
		 * The finished barcode shape
		 */
		public function get barcodeShape():Shape {
			return _barcodeShape;
		}

		/**
		 * Regenerates the barcode when properties are committed
		 */
		override protected function commitProperties():void {
			super.commitProperties();
			debug('commitProperties()');
			if(_barcodeShape != null && contains(_barcodeShape)) {
				$removeChild(_barcodeShape);
			}			
			try { 
				_barcodeShape = Pdf417lib.generateBarcode(_barcodeText);
				_barcodeShape.scaleY = 3;  // necessary for some scanners
			} catch (e:Error) {
				debug( 'Warning: ' + e.message );
				dispatchEvent( new Pdf417Event( Pdf417Event.BARCODE_ERROR, false, false, e.message ) );
			}
			invalidateSize();
			invalidateDisplayList();
			
		}

		/**
		 * Calculate the desired with and height based on the height 
		 * and width of the barcode
		 */
		override protected function measure():void {
			debug('measure()');
			if(_barcodeShape) {
				measuredWidth = measuredMinWidth = _barcodeShape.width;
				measuredHeight = measuredMinHeight = _barcodeShape.height;
			}
		}
		
		/**
		 * Update the display
		 */
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
			debug('updateDisplayList('+arguments+')');
			if(_barcodeShape!=null){				
				$addChild(_barcodeShape);	
			}
			super.updateDisplayList(unscaledWidth, unscaledHeight);			
		}
		
		protected function debug(s:String) :void{
			if(debugEnabled) trace('[Pdf417Barcode] '+s);
		}		
	}
}
